#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Oct 18 11:23:28 2018

@author: james
"""

import cv2
import requests
import json
import time
import base64
import numpy as np

access_token="24.e0618c7ed1a2d40040618d1c39c2781b.2592000.1542192711.282335-10917211"
access_key=""


face_num=0
frame=None
now_time=0

def do_xugu_unlock(lock=True):
    pass

def b64_to_cvimg(b64):
    imgData = base64.b64decode(b64)
    nparr = np.frombuffer(imgData, np.uint8)
    img = cv2.imdecode(nparr, cv2.IMREAD_COLOR)
    return img

def cvimg_to_b64(img):
    image = cv2.imencode('.jpg', img)[1]
    base64_data = str(base64.b64encode(image))[2:-1]
    return base64_data


def face_search(img64):
    url="https://aip.baidubce.com/rest/2.0/face/v3/search"
    url=url+"?access_token="+access_token
    data={
            "image":img64,
            "image_type":"BASE64",
            "group_id_list":"test_group"}
    try:
        response=requests.post(url,files=None,data=data)
        res_text=response.text
        res_json=json.loads(res_text)
        return res_json
    except Exception:
        return "error"

def get_face_info(img64):
    url="https://aip.baidubce.com/rest/2.0/face/v3/detect"
    url = url + "?access_token=" + access_token
    url="https://sped.bsmaker.cn/ai/get_face_info"
#    data = {"image_type":"BASE64",
#            "group_id_list":group_id,
#            "image":img,
#            "max_user_num":user_top_num,
#            "liveness_control":"NORMAL"}
    data={"company_id":"10000",
          "access_token":access_token,
          "img":img64}
    try:
        response = requests.post(url,files=None,data=data)
        res_text=response.text
        res_json=json.loads(res_text)
        return res_json
    except Exception:
        return "error"
    
def post_request(frame,face_num,nt):
    if(face_num>0) and (time.time()-nt>3):
        global now_time
        now_time=time.time()
        #print(now_time)
        img64=cvimg_to_b64(frame)
        res=face_search(img64)
        try:
            scores=(res["result"]["user_list"][0]["score"])
            print(str(scores))
            if(scores>80):
                do_xugu_unlock(True)
            else:
                do_xugu_unlock(False)
        except Exception:
            pass
        time.sleep(3)

def faceDetect(img64,face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml'),divisor=8):
    try:
        img=b64_to_cvimg(img64)
    except Exception as e:
        return "error",0
    size=img.shape[:2]
    h,w=size
    minSize=(w//divisor,h//divisor)
    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    faces = face_cascade.detectMultiScale(gray, 1.2, 3,cv2.CASCADE_SCALE_IMAGE,minSize)
    for (x,y,w,h) in faces:
        cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2)
    img=cvimg_to_b64(img)
    return img,len(faces)

